package com.dc.util;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.List;

import static com.dc.util.ExcelUtil.getHSSFWorkbook;

/**
 * 导出工具类
 */
@Slf4j
public class ExportUtil {

    private static final Logger logger = LoggerFactory.getLogger(ExportUtil.class);


    /**
     * 导出Excel
     *
     * @param excelName 文件名
     * @param dataList  导出的数据
     * @param response  response
     */
    public static void exportExcel(String excelName, List<? extends Object> dataList, HttpServletResponse response) {
        if (StringUtils.isBlank(excelName)) {
            excelName = "";
        }
        try {
            String fileName = excelName + "_" + System.currentTimeMillis() + ".xls";
            HSSFWorkbook wb = getHSSFWorkbook(excelName, dataList);
            fileName = new String(fileName.getBytes(), "ISO8859-1");

            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

            ServletOutputStream out = response.getOutputStream();
            try {
                wb.write(out);
                out.flush();
            } catch (Exception e) {
                logger.error("导出Excel-文件写入异常：{}", e.getMessage());
            } finally {
                out.close();
            }
        } catch (Exception e) {
            logger.error("导出Excel异常：{}", e.getMessage());
        }
    }

    /**
     * 导出Excel
     *
     * @param excelName 文件名
     * @param dataList  导出的数据
     * @param response  response
     */
    public static void exportExcelNew(String excelName, List<? extends Object> dataList, Class<?> entity, HttpServletResponse response) {
        if (StringUtils.isBlank(excelName)) {
            excelName = "";
        }
        ExportParams exportParams = new ExportParams(excelName, "");
        exportParams.setStyle(ExcelExportStyler.class);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams,
                entity, dataList);
        String fileName = excelName + "_" + System.currentTimeMillis() + ".xls";
        try {
            fileName = new String(fileName.getBytes(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setContentType("application/octet-stream;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        try {
            //对导出的excel的单元格数据进行换色
            initDataStyle(workbook);
            workbook.write(response.getOutputStream());
            workbook.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void initDataStyle(Workbook workbook) {
        //取第一个sheet
        Sheet sheetAt = workbook.getSheetAt(0);
        //获取最后一行的下标
        int lastRowNum = sheetAt.getLastRowNum();
        //遍历每一行
        for (int i = 2; i <= lastRowNum; i++) {
            //获取每一行
            Row row = sheetAt.getRow(i);
            //行为空不读取
            if (row == null) continue;
            //获取该行最后一个单元格下标
            short lastCellNum = row.getLastCellNum();
            //对该行单元格进行遍历
            for (short j = 0; j < lastCellNum; j++) {
                Cell cell = row.getCell(j);
                if (null != cell && "tt1".equals(cell.getStringCellValue())) {
                    CellStyle style = workbook.createCellStyle();
                    //填充单元格背景色
                    style.setFillForegroundColor(IndexedColors.GREEN.getIndex());
                    style.setFillPattern(FillPatternType.SOLID_FOREGROUND); ////填充模式--必须设置
                    cell.setCellStyle(style);
                    System.out.println("设置cell颜色");
                }
            }
        }
    }

    /**
     * 下载模板文件
     *
     * @param response
     * @param inFileName
     * @param outFileNam
     */
    public static void downloadExcel(HttpServletResponse response, String inFileName, String outFileNam) {
        InputStream inputStream = null;
        try {
            response.resetBuffer();
            //设置输出文件格式
//            response.setContentType("application/vnd.ms-excel");
//            response.addHeader("Access-Control-Allow-Origin", "*");
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(outFileNam.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
            ServletOutputStream outputStream = response.getOutputStream();
            inputStream = ExportUtil.class.getResourceAsStream("/static/" + inFileName);
//            File f = new File("C:\\Users\\23329\\Desktop"+inFileName);
//            inputStream = new FileInputStream(f);
            byte[] buff = new byte[1024];
            int length;
            while ((length = inputStream.read(buff)) != -1) {
                outputStream.write(buff, 0, length);
            }
            if (outputStream != null) {
                outputStream.flush();
                outputStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {

                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error("关闭资源出错" + e.getMessage());
                    e.printStackTrace();
                }
            }
        }
    }

    public static void exportSetCode(Workbook workbook, String excelName, HttpServletResponse response) {
        String fileName = excelName + "_" + System.currentTimeMillis() + ".xls";
        try {
            fileName = new String(fileName.getBytes(), "ISO8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setContentType("application/octet-stream;charset=ISO8859-1");
        response.setHeader("Pragma", "No-cache");//设置不要缓存
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        try {
            workbook.write(response.getOutputStream());
            workbook.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
